<template>
  <view class="server">
    <head-box></head-box>
    <view class="tab-botton">
      <view class="content">
        <view class="main">
          <view class="title" v-if="0">
            <view class="left">
              <text>我的应用</text>
            </view>

          </view>
          <view class="iconList" v-if="0">
            <draggable :disabled="!edit" class="ul-draggable" element="ul" v-model="navList">
              <block v-for="(item,index) in navList" :key="index" >
                <view class="data" :class="index>=4?'datas':''" @click="onDel(item,index)" >
                  <view class="icon" @click="!edit && onWebView(item)">
                    <image :src="item.icon" class="images"></image>
                    <image v-if="edit" src="/static/home-edit/delete.png" class="images1"></image>
                  </view>
                  <view class="text">
                    {{item.title}}
                  </view>
                </view>
              </block>
            </draggable>
          </view>
        </view>
      </view>

      <view class="content" v-for="(k,v) in list1" :key="v">
        <view class="main">
          <view class="title">
            <view class="left">
              <text>{{k.leftName}}</text>
            </view>
          </view>

          <view class="iconList">
            <draggable :disabled="!edit" element="ul" v-model="k.navList" class="ul"
                       @change="onSelectEnd"
            >
            <block v-for="(item,index) in k.navList" :key="item.id">
              <view class="data list-group-item" :class="index>=4?'datas':''" @click="onWebView(item,index)">
                <view class="icon">
                  <image :src="$imageUrl+item.icon" class="images" v-if="item.icon"></image>
                  <image v-if="0" src="/static/home-edit/add.png" class="images1"></image>
                </view>
                <view class="text">
                  {{item.name}}
                </view>
              </view>
            </block>
            </draggable>
          </view>

        </view>
      </view>
      <view class="right edit">
        <button @click="onEdit" class="_main-content-btn _main-content-btn1"><text>{{edit?'长按图标拖拽编辑':'编辑首页'}}</text></button>
        <button @click="onSave" class="_main-content-btn _main-content-btn2" v-if="edit"><text>保存</text></button>
        <button class="_main-content-btn _main-content-btn3" @click="onRest"><text>恢复至默认排序</text></button>
      </view>
    </view>


    <tabs-box></tabs-box>
  </view>
</template>

<script>
import draggable from "vuedraggable"
import {gpMoveTypeList,getMoveTypeRefresh,setMoveType} from '@/api/home-type'
import {getGroupsCategoryList} from '@/common/type'
export default {
  components: {
    draggable
  },

  data() {
    return {
      enabled: true,
      dragging: false,
      edit: false,
      //我的应用中一开始的
      navList: [],
      //所有数据集
      list1: [],
      list2:[],//被选择后的数据
      list3:[],//最终给的id
    };
  },
  onLoad(){
    this.getMoveTypeRefresh()
  },
  mounted() {
  },
  methods: {
    //恢复至默认排序
    onRest(){
      uni.showModal({
        title: '提示',
        content: '是否恢复至默认排序',
        success: res=> {
          if (res.confirm) {
            this.setMoveTypes('','b')
          } else if (res.cancel) {
            this.$api.msg('已取消恢复至默认排序操作')
          }
        }
      });
    },
    //首页分类-获取
    getMoveTypeRefresh(){
      getMoveTypeRefresh().then(res=>{
        const {code,result} = res
        if(!result.length || result===''){
          this.gpMoveTypeList()
        } else {
          this.getGroupsCategory(result)
        }

      })
    },
    //查询想要的数据
    getGroupsCategory(list){
      this.list1 = getGroupsCategoryList ( list )
    },
    //首页分类-分页列表查询
    gpMoveTypeList(){
      gpMoveTypeList({pageSize:999}).then((res) =>{
        const {result:{records}} = res
        this.getGroupsCategory(records)
      })
    },
    onSelectEnd({moved:{element:{id}}}){
      this.list2.push({id})
      const hash = {};
      const newArr = this.list2.reduce((item, next) => {
        hash[next.id] ? '' : hash[next.id] = true && item.push(next);
        return item
      }, []);
      console.log(newArr);
    },
    //跳转列表对应页面
    onWebView(item,index){

      if(!this.edit){
        if(item.category===4){
          if(item.code==='498'){
            this.$api.handleMenu(`/pages/liveVideo/liveVideo`)
          } else if(item.code==='499'){
            this.$api.handleMenu(`/pages/liveActivity/liveActivity`)
          }else {
            uni.navigateTo({
              url:`/pages/ElegantDemeanour/ElegantDemeanour?code=${item.cid || 0}&state=${item.cid || 0}`,
            })
          }
        }
        else if(item.url){
          if(item.url.startsWith('/pages/')){
            this.$api.handleMenu(item.url)
          }else if(item.url.includes('https') || item.url.includes('http')){
            this.$api.handleMenu(`/pages/webview/webview?url=${item.url}`)
          } else {
            this.$api.handleMenu('/'+item.url)
          }
        }

      }
    },
    //编辑状态
    onEdit() {
      this.edit = !this.edit
    },
    //保存
    onSave(){
      if(this.edit){
        this.setMoveType()
      }
    },
    //排序操作
    sortClass(sortData){
      const groupBy = (array, f) => {
        let groups = {};
        array.forEach((o) => {
          let group = JSON.stringify(f(o));
          groups[group] = groups[group] || [];
          groups[group]=o;
        });
        return Object.keys(groups).map((group) => {
          return groups[group];
        });
      };
      const sorted = groupBy(sortData, (item) => {
        return item.code; // 返回需要分组的对象
      });
      return sorted;
    },
    //保存设置
    setMoveType(){
      this.$api.showLoading({title:'保存中'})
       //深拷贝源数据
      let arr =this.list1
      let list = []
      arr.map(temp=>{
        temp.navList.map(child=>{
          list.push({
            id:child.id
          })
        })
      })
      // const tempList= this.sortClass(list)

      // 循环遍历原始数据
      this.setMoveTypes(JSON.stringify(list))

    },
    //保存设置
    setMoveTypes(list,type='a'){
      setMoveType(list).then(res=>{
        const {message,
          result,code
        } =res
        this.$api.hideLoading()
        if(code===200){
          this.$api.msg(result)
          if(type==='a'){
            this.$api.leftBack()
          } else {
            this.getMoveTypeRefresh()
          }

        } else {
          this.$api.msg(message)
        }
      }).catch(e=>{
        this.$api.hideLoading()
        console.log ( e )
      })
    },
    //删除状态
    onDel(item,index) {
      if (this.edit) {
        //如果有有isCommonly,则为常用的
        if(item.isCommonly){
          const {icon, id, isCommonly, title, url} = item
          this.navList.splice(index, 1)
          this.list1[this.list1.length-1].navList.push({
            id,
            title,
            icon,
            url,
            isCommonly
          })

        } else {
          const pt = this.navList[index]
          const {
            pageIndex,
            childIndex,
            id,
            title,
            icon,
            url
          } = pt
          if (this.list1[pageIndex]) {
            this.navList.splice(index, 1)
            this.list1[pageIndex].navList.splice(childIndex, pageIndex,

                {
                  id,
                  title,
                  icon,
                  url
                })
          }

        }
      }
    },
    //添加
    onAdd(a, b) {
      if (this.edit) {
        this.navList.push({
          id: this.list1[a].navList[b].id,
          title: this.list1[a].navList[b].title,
          icon: this.list1[a].navList[b].icon, //控制定位的icon
          url: this.list1[a].navList[b].url, //所要跳转的url地址
          name: this.list1[a].leftName,
          pageIndex: a,
          childIndex: b,
        })
        this.list1[a].navList.splice(b, 1)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.server {
  background: #F6F6F6;
  padding-bottom: 150rpx;
}
.content {
  margin: 0 25rpx 20rpx 25rpx;
  background: #FFFFFF;
  border-radius: 15rpx;
  .main {
    .title {
      padding: 21rpx 25rpx 0 25rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .left {
        font-size: 30rpx;
        font-family: PingFang;
        font-weight: bold;
        color: #222222;
      }
      .edit {
        color: #222222;
        text{
          color: #4F73FE;
          margin-right: 10rpx;
        }
      }
    }

    .iconList {
      margin-top: 30rpx;
      width: auto;
      border-radius: 5rpx;
      display: flex;
      justify-content: flex-start;
      white-space: nowrap;
      flex-wrap: wrap;
      .data {
        margin-bottom: 30rpx;
        box-sizing: border-box;
        text-align: center;
        .icon {
          flex-grow: 1;
          position: relative;
          .images {
            width: 45rpx;
            height: 43rpx;
          }
          .images1 {
            width: 27rpx;
            height: 27rpx;
            border-radius: 50%;
            position: absolute;
            right: 30%;
            top: -10rpx;
            transform: translate(60%, 0);
          }
        }
        .text {
          width: 100%;
          padding: 7rpx 26rpx;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          font-size: 24rpx;
          font-family: PingFang;
          font-weight: 500;
          color: #222222;
        }
      }
    }
  }
}
.list-group {
  width: 100%;
  height: auto;
}
.list-group-item_img {
  position: absolute;
  width: 16px;
  right: 0;
  margin-right: 4px;
}
.list-group-item_img2 {
  position: absolute;
  width: 18px;
  right: 0;
  margin-right: 4px;
}
.list-group-item {
  cursor: move;
  width:25%;
}
.list-group-item-div {
  padding: 10px 0px;
}
.ul-draggable {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
}
.ul{
  padding:0;
  flex:1;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
.right{

  text-align: center;
  padding: 10px;
  font-size: 30rpx;
  color: #222;

}
._main-content-btn {
  font-size: 30rpx;
  border-radius: 40rpx;
  color: #fff;
  background: #3f8fee;
  border: none;

  width: 80%;
}
._main-content-btn1{
  margin-top: 80rpx;
}
._main-content-btn2{
  margin-top: 40rpx;
}
._main-content-btn3{
  margin-top: 40rpx;
  background: #f90;
}
</style>
